package lm.concurrency.day1;

import lombok.extern.slf4j.Slf4j;

/**
 * @Auther: Min.Liu
 * @Description: 线程休眠被打断
 * @Date: Created in 17:11 2024/6/3
 */
@Slf4j
public class SleepWithInterruptTest {
    public static void main(String[] args) throws InterruptedException {
        //test1();
        test2();
    }

    private static void test2() throws InterruptedException {
        Thread t1 = new Thread(() -> {
            while(true) {
                boolean interrupted = Thread.currentThread().isInterrupted();
                if(interrupted) {
                    log.debug("被打断了, 退出循环");
                    //Thread.currentThread().isInterrupted() 会返回打断状态  不会清除打断标记
                    //Thread.interrupted()                 也会返回打断状态   但是会清除打断标记
                    System.out.println(Thread.interrupted());
                    System.out.println(Thread.currentThread().isInterrupted());
                    break;
                }
                try {
                    Thread.sleep(1000);
                    System.out.println(Thread.interrupted());
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        }, "t1");
        t1.start();

        Thread.sleep(5000);
        log.debug("interrupt");
        t1.interrupt();
    }

    private static void test1() throws InterruptedException {
        Thread t1 = new Thread("t1") {
            @Override
            public void run() {
                log.debug("enter sleep...");
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    log.debug("wake up...");
                    e.printStackTrace();
                }
            }
        };
        t1.start();

        Thread.sleep(1000);
        log.debug("interrupt...");
        t1.interrupt();
        Thread.sleep(1000);
        log.debug("打断标记:{}", t1.isInterrupted());
    }
}
